import {syncCapture} from "@/utils/index.ts";
import { storeNameType } from "@/interface/store";

const $store_set = (name: storeNameType, value: any): boolean => {
  syncCapture(() => window.localStorage.setItem(name, JSON.stringify(value)));
  return true;
}

const $store_get = (name: storeNameType): any => {
  const data: string = window.localStorage.getItem(name) as string;
  try {
    return JSON.parse(data);
  } catch (error) {
    return data;
  }
};

const $store_get_all = () => {
  let index = 0;
  const storeMap = {};
  syncCapture(() => {
    while (window.localStorage.key(index)) {
      const key = window.localStorage.key(index) as string;
      // @ts-ignore
      storeMap[key] = $store_get(key);
      index++;
    }
  })
  return storeMap;
}

const $store_remove = (name: storeNameType) => window.localStorage.removeItem(name);
const $store_clear = () => window.localStorage.clear();

export {
  $store_set,
  $store_get,
  $store_get_all,
  $store_remove,
  $store_clear
}
